package br.com.sistemasaude.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.com.sistemasaude.bean.Material;
import br.com.sistemasaude.bean.Medicamento;
import br.com.sistemasaude.util.JpaUtil;

public class MaterialDAOImpl implements MaterialDAO{
	
private final GenericDAO<Material> dao;	
	
	EntityManager em = new JpaUtil().getEntityManager();
	
	public MaterialDAOImpl() {
		dao = new GenericDAO<Material>(em, Material.class);
		}
	
	public void salvar(Material material) {
		
		try {

			em.getTransaction().begin();
			dao.salvar(material);
			em.getTransaction().commit();

		} catch (Exception e) {
			
			em.getTransaction().rollback();
			e.printStackTrace();
			
		} finally {
			em.close();
		}
		
	}
	
	public boolean remove(Material material){
		try {

			em.getTransaction().begin();
			dao.remove(material);
			em.getTransaction().commit();
			return true;
		} catch (Exception e) {
			
			em.getTransaction().rollback();
			e.printStackTrace();
			return false;
			
		} finally {
			em.close();
		}
	}
	
	public boolean update(Material material){
		try {

			em.getTransaction().begin();
			dao.update(material);
			em.getTransaction().commit();
			return true;

		} catch (Exception e) {
			
			em.getTransaction().rollback();
			e.printStackTrace();
			return false;
		} finally {
			em.close();
		}
		
	}
	
	public List<Material> listar(){
		
		List<Material> listaMateriais = new ArrayList<Material>();
		try {

			listaMateriais = dao.listar();

		} catch (Exception e) {
			
			e.printStackTrace();
			
		} finally {
			em.close();
		}
		
		return listaMateriais;
		
	}
	

	public Material localizaMaterial(String material){
			
			EntityTransaction t = em.getTransaction();
			Material mat = null;
			try {

				t.begin();
				Query q =  em.createQuery("select m from Material m where m.descricao like:pMaterial");
				q.setParameter("pMaterial", material);
				mat = (Material) q.getSingleResult();
				
				t.commit();
				

			} catch (Exception e) {

				e.printStackTrace();
				if (t.isActive()) t.rollback();

			} finally {

				em.close();
			}
			
			return mat;

		}



}
